<script lang="ts" setup>
import type { VxeGridListeners, VxeGridProps } from '#/adapter/vxe-table';

import { h, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { kickoutByTokenValue, logoutByTokenValue } from '#/api/sys/user';
import { TableAction } from '#/components/table-action';
import { getRelativeTime } from '#/util/tool';

const emits = defineEmits(['reload']);
const record = ref();
const [Modal, modalApi] = useVbenModal({
  footer: false,
  onOpenChange(isOpen) {
    record.value = isOpen ? modalApi.getData()?.record : {};
    if (isOpen) {
      dataSource.value = record.value.tokenList || [];
    }
  },
});

const dataSource = ref([]);
const handlePage = (params: any) => {
  const { pageNum, pageSize } = params;
  return Promise.resolve({
    recordCount: dataSource.value.length,
    totalPage: Math.ceil(dataSource.value.length / pageSize),
    rows: dataSource.value.slice((pageNum - 1) * pageSize, pageNum * pageSize),
  });
};
const gridOptions: VxeGridProps<any> = {
  columns: [
    { field: 'tokenValue', title: 'Token凭证' },
    {
      field: 'loginTime',
      title: '登录于',
      slots: {
        default: ({ row }) => {
          return h('div', { class: 'text-center' }, [
            h('span', `${row.loginTime} - `),
            h(
              'span',
              {
                style: {
                  color: 'green',
                },
              },
              getRelativeTime(row.loginTime),
            ),
          ]);
        },
      },
    },
    { field: 'loginIp', title: '登录IP' },
    { field: 'loginBrowser', title: '浏览器' },
    {
      field: 'expireTime',
      title: '凭证失效于',
      slots: {
        default: ({ row }) => {
          return h('div', { class: 'text-center' }, [
            h('span', `${row.expireTime} - `),
            h(
              'span',
              {
                style: {
                  color: 'green',
                },
              },
              getRelativeTime(row.expireTime),
            ),
          ]);
        },
      },
    },
    {
      width: 160,
      title: '操作',
      align: 'center',
      slots: { default: 'ACTION' },
      fixed: 'right',
    },
  ],
  toolbarConfig: {
    refresh: false, // 刷新
    print: false, // 打印
    export: false, // 导出
    // custom: true, // 自定义列
    zoom: true, // 最大化最小化
    // slots: {
    //   buttons: 'toolbar-buttons',
    // },
    custom: {
      // 自定义列-图标
      icon: 'vxe-icon-menu',
    },
  },
  border: false,
  height: '500',
  keepSource: true,
  pagerConfig: {},
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        return await handlePage({
          pageNum: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
      },
    },
  },
};
const gridEvents: VxeGridListeners<any> = {};
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions,
  gridEvents,
});
const handleDelete = (record: any, type: string) => {
  const ids: any = [];
  if (record && record.tokenValue) {
    ids.push(record.tokenValue);
  }
  const api =
    type === 'logoutByTokenValue' ? logoutByTokenValue : kickoutByTokenValue;
  const msg = type === 'logoutByTokenValue' ? '强制注销成功' : '踢下线成功';
  api({
    ids,
  }).then(() => {
    message.success(msg);
    dataSource.value = dataSource.value.filter(
      (item: any) => !ids.includes(item.tokenValue),
    );
    gridApi.reload();
    emits('reload');
  });
};
defineExpose(modalApi);
</script>
<template>
  <Modal class="w-[60%]" title="在线用户详情">
    <Grid>
      <template #toolbar-actions>
        账号 {{ record.userName }} （{{ record.realName }}）目前已在
        {{ record.tokenList?.length }} 个客户端登录
      </template>
      <template #ACTION="{ row }">
        <TableAction
          :actions="[
            {
              label: '踢下线',
              size: 'small',
              popConfirm: {
                title: '确定踢下线吗？',
                confirm: handleDelete.bind(null, row, 'kickoutByTokenValue'),
              },
              disabled: row.isCurrentUser || row.superAdmin,
              tooltip:
                row.isCurrentUser || row.superAdmin
                  ? '当前用户或超级管理员不允许踢下线！'
                  : undefined,
              auth: ['admin', 'sys:user:kickoutByTokenValue'], // 根据权限控制是否显示: 有权限，会显示
            },
            {
              label: '强制注销',
              size: 'small',
              popConfirm: {
                title: '确定强制注销吗？',
                confirm: handleDelete.bind(null, row, 'logoutByTokenValue'),
              },
              disabled: row.isCurrentUser || row.superAdmin,
              tooltip:
                row.isCurrentUser || row.superAdmin
                  ? '当前用户或超级管理员不允许强制注销！'
                  : undefined,
              auth: ['admin', 'sys:user:logoutByTokenValue'], // 根据权限控制是否显示: 有权限，会显示
            },
          ]"
        />
      </template>
      <template #toolbar-tools></template>
    </Grid>
  </Modal>
</template>
